import {Category, CategoryMap, Tag, useTags} from '../../hooks/useTags';
import React, {useState} from 'react';
import {Editor} from '../../components/Editor';
import {ButtonList, DeleteButton, SaveButton} from '../../components/Button';
import {useHistory} from 'react-router-dom';
import {CategorySelector} from '../../components/CategorySelector';
import {TagInfoWrapper} from 'components/TagInfoWrapper';
import {useRecords} from '../../hooks/useRecords';

type Props = {
  tag: Tag
}

const TagContent: React.FC<Props> = (props) => {
  // 注意 useTags() 一定要放在 useRecords() 后面，不然会产生无法修改或删除标签的bug
  const {findRecordsByTagId, moveRecordsByTagId} = useRecords()
  const {doesTagNameExist, updateTag, deleteTag} = useTags();
  const [selectedCategory, setSelectedCategory] = useState<Category>(props.tag.category);
  const [tagName, setTagName] = useState(props.tag.name);
  const history = useHistory();
  const onSave = () => {
    if (tagName !== props.tag.name && doesTagNameExist(tagName)) {
      alert(`标签名「${tagName}」已存在，不可重复设置`)
      return;
    }
    const recordCount = findRecordsByTagId(props.tag.id).length
    let message = ''
    if (recordCount){
      message += `该标签下已有${recordCount}条账目记录，修改后这些记录也将被修改。\n`
    }
    message += '确认要修改标签吗？'
    if (!window.confirm(message)) return;
    updateTag(props.tag.id, {name: tagName, category: selectedCategory});
    alert('修改成功');
    history.goBack();
  };
  const onDelete = () => {
    const recordCount = findRecordsByTagId(props.tag.id).length
    const category = CategoryMap[props.tag.category]
    let message = ''
    if (recordCount){
      message += `该标签下已有${recordCount}条账目记录，删除后这些记录将被移入「其它${category}」。\n`
    }
    message += '确认要删除标签吗？'
    if (!window.confirm(message)) return;
    deleteTag(props.tag.id);
    if (recordCount) {moveRecordsByTagId(props.tag.id)}
    alert('删除成功');
    history.goBack();
  };
  const cantSave = () => tagName === props.tag.name && selectedCategory === props.tag.category
  const isEditable = () => props.tag.name !== '其它收入' && props.tag.name !== '其它支出'

  return (
    <>
      <TagInfoWrapper>
        <Editor label="标签名" type="text" placeholder={tagName}
                value={tagName} onChange={(e) => {if(isEditable()) setTagName(e.target.value);}}/>
      </TagInfoWrapper>
      <TagInfoWrapper>
        <CategorySelector value={selectedCategory} onClick={(s) => {if(isEditable()) setSelectedCategory(s);}}/>
      </TagInfoWrapper>

      {
        isEditable() &&
        <ButtonList>
          <SaveButton onClick={onSave} disabled={cantSave()}>保存修改</SaveButton>
          <DeleteButton onClick={onDelete}>删除标签</DeleteButton>
        </ButtonList>
      }
    </>
  );
};

export {TagContent};